import { Component, OnInit, Input } from '@angular/core';
import { PropertyService } from '../service/property.service';
import { PropertyType, CRUD_MODE, PropertySaleStatus } from '../../shared/config/app-settings';
import { ActivatedRoute, Router } from '@angular/router';
import * as _ from 'lodash';
import { StatisticsUtilsService } from '../../shared/services/statistics-utils.service';
import { TranslateService } from '@ngx-translate/core';
import { UserService } from '../../shared/services/user.service';
@Component({
  selector: 'app-sales-record',
  templateUrl: './sales-record.component.html',
  styleUrls: ['./sales-record.component.css']
})
export class SalesRecordComponent implements OnInit {
  @Input()
  userId: number;
  cols: Array<any> = [];
  selectedColumns: Array<any> = [];
  records: Array<any> = [];
  optionStatus: any[];


  totalCommisionUnit = 0;
  totalCommission = 0;
  constructor(
    private PropertyService: PropertyService,
    private router: Router,
    private route: ActivatedRoute,
    private userService:UserService,
    private translateService: TranslateService,
    private statisticsUtilsService: StatisticsUtilsService) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      console.log('login userid :user-id from parameter {}: from input {}', params['user-id'], this.userId);
      this.userId = _.isEmpty(params['user-id']) ? this.userId : +params['user-id'];

      this.cols = [
        { field: 'id', header: this.translateService.instant('ID') },
        // { field: 'purchaseDate', header: this.translateService.instant('DATE') },
        { field: 'buildingAddress', header: 'PROJECT ADDRESS' },
        { field: 'clientSurname', header: 'CLIENT SURNAME' },
        { field: 'lot', header: 'LOT#' },
        { field: 'total_commission_sale', header: 'TOTAL COMMISSION' },
        { field: 'current_commission_sale', header: 'COMMISSION PAID' },
        { field: 'sellingPrice', header: 'SOLD PRICE' },
        { field: 'sale_status', header: 'STATUS' }
        // { field: 'sale_status', header: this.translateService.instant('Property Management') }
      ];

      this.userService.getUserById(this.userId).subscribe((user) => {
        
        console.log('shared user', user);
        if (user.userType === "1") {
          this.cols.splice(4, 1);
        }
        console.log(this.cols);

        this.selectedColumns = _.cloneDeep(this.cols); //toggle cols
        this.selectedColumns.splice(0, 1); //default hide first column

        // In a real app: dispatch action to load the details here.
        this.load();
      });

     
    });

    this.optionStatus = [
      { label: PropertySaleStatus.FOR_SALE, value: PropertySaleStatus.FOR_SALE },
      { label: PropertySaleStatus.CONTRACT_EXCHANGED, value: PropertySaleStatus.CONTRACT_EXCHANGED },
      { label: PropertySaleStatus.DEPOSIT_TAKEN, value: PropertySaleStatus.DEPOSIT_TAKEN },
      { label: PropertySaleStatus.SETTLED, value: PropertySaleStatus.SETTLED }
    ];

  }

  load() {
    let filter = {
      agentId: this.userId,
      type: PropertyType.SALE
    };
    this.PropertyService.getAllProperties(filter).subscribe(
      data => {
        this.records = _.filter(data, (item) => {
          return item.sale_status === PropertySaleStatus.CONTRACT_EXCHANGED ||
            item.sale_status === PropertySaleStatus.SETTLED ||
            item.sale_status === PropertySaleStatus.DEPOSIT_TAKEN;
        });
        console.log("load my sales records :", this.records);
        _.each(this.records, (item) => {
          item.buildingAddress = item.propertyList ? item.propertyList.buildingAddress : '';
          item.clientSurname = item.owner ? item.owner.lastName : '';
        });

        this.records = _.sortBy(this.records, 'purchaseDate');
        console.log("load my sales records after sort:", this.records);

      },
      err => {
        console.log(err);
      }
    );

    this.loadStatistics();
  }

  loadStatistics() {
    this.statisticsUtilsService.getSalesRecordStat(this.userId).subscribe((res) => {
      this.totalCommisionUnit = res['totalCommisionUnit'];
      this.totalCommission = res['totalCommission'];
    });
  }

  onViewRow(rowData) {
    this.router.navigate(['../../property-detail/' + rowData.id], { relativeTo: this.route, queryParams: { mode: CRUD_MODE.VIEW,menuKey :'house-detail' } });
  }




}
